package com.carbon.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carbon.common.core.domain.AjaxResult;
import com.carbon.common.core.text.Convert;
import com.carbon.common.utils.DateUtils;
import com.carbon.domain.Batch;
import com.carbon.domain.Check;
import com.carbon.domain.Ware;
import com.carbon.dto.BatchDto;
import com.carbon.dto.CheckDto;
import com.carbon.dto.WareDto;
import com.carbon.service.BatchService;
import com.carbon.service.CheckService;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.carbon.service.WareService;
import com.carbon.utils.OrderIdUtil;
import com.carbon.vo.SearchParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

/**
 * 盘点信息(Check)表控制层
 *
 * @author WangFK
 * @since 2023-09-05 08:50:12
 */
@RestController
@Slf4j
@RequestMapping("/wms/check")
public class CheckController {
    /**
     * 服务对象
     */
    @Resource
    private CheckService checkService;
    @Resource
    private WareService wareService;

    @Resource
    private BatchService batchService;

    /**
     * 获取全部非洲人
     *
     * @return
     */
    @GetMapping("/createByListInfo")
    public AjaxResult createByListInfo() {
        List<String> collect = checkService.list().stream().map(Check::getCreateBy).distinct().collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

    /**
     * 修改盘点状态
     *
     * @param id
     * @param checkStatus
     * @return
     */
    @PutMapping("/changeCheckStatus")
    public AjaxResult changeCheckStatus(String id, String checkStatus) {
        LambdaUpdateWrapper<Check> lqw = new LambdaUpdateWrapper<Check>()
                .eq(Check::getId, id)
                .set(Check::getCheckStatus, checkStatus);
        return checkService.update(lqw) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list(SearchParams params) {
        String search = params.getSearch();
        List<String> wareList = params.getWareList();
        List<String> productNameList = params.getProductNameList();
        Page<Check> checkPage = new Page<>(params.getPageNum(), params.getPageSize());
        LambdaUpdateWrapper<Check> lqw = new LambdaUpdateWrapper<Check>()
                .eq(ObjectUtil.isNotEmpty(params.getGoodsType()), Check::getGoodsType, params.getGoodsType())
                .eq(ObjectUtil.isNotEmpty(params.getCheckType()), Check::getCheckType, params.getCheckType())
                .orderByAsc(Check::getSort)
                .orderByAsc(Check::getId);
        if (ObjectUtil.isNotEmpty(params.getDateTime())) {
            lqw.like(Check::getCreateTime, params.getDateTime()).or()
                    .like(Check::getWareMon, params.getDateTime());
        }
        if (ObjectUtil.isNotEmpty(wareList)) {
            lqw.eq(Check::getWareId, wareList.get(wareList.size() - 1));
        }
        if (ObjectUtil.isNotEmpty(productNameList)) {
            lqw.eq(Check::getBatchId, productNameList.get(productNameList.size() - 1));

        }

        if (ObjectUtil.isNotEmpty(search)) {
            lqw.like(Check::getOrderId, search).or()
                    .like(Check::getCreateBy, search);
        }
        checkPage = checkService.page(checkPage, lqw);
        List<Check> records = checkPage.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return AjaxResult.success();
        }
        List<CheckDto> checkDtos = BeanUtil.copyToList(records, CheckDto.class);

        checkDtos.stream().forEach(item -> {
            Batch batch = batchService.getProductByBatchId(item.getBatchId());
            if (ObjectUtil.isNotEmpty(batch)) {
                item.setProductName(batch.getProductName());
                item.setBatchName(batch.getBatchId());
            }
            WareDto wareDto = wareService.getWareNodeById(item.getWareId());
            if (ObjectUtil.isNotEmpty(wareDto)) {
                item.setWarePositionDto(wareDto.getWarePositionDto());
                item.setWareNameDto(wareDto.getWareNameDto());
                item.setWareAreaDto(wareDto.getWareAreaDto());
            }
        });
        return AjaxResult.success()
                .put("rows", checkDtos)
                .put("total", checkPage.getTotal());
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public AjaxResult selectOne(@PathVariable Serializable id) {
        Check byId = checkService.getById(id);
        CheckDto checkDto = new CheckDto();
        BeanUtil.copyProperties(byId, checkDto);
        BatchDto productIdByBatchId = batchService.getProductIdByBatchId(checkDto.getBatchId());
        if (ObjectUtil.isNotEmpty(productIdByBatchId)) {
            ArrayList<Integer> strings = new ArrayList<>();
            strings.add(Convert.toInt(productIdByBatchId.getProductId()));
            strings.add(Convert.toInt(productIdByBatchId.getBatchId()));
            checkDto.setProductNameList(strings);
        }

        WareDto wareDto = wareService.getWareIdNodeById(byId.getWareId());
        if (ObjectUtil.isNotEmpty(wareDto)) {
            ArrayList<Integer> strings = new ArrayList<>();
            strings.add(Convert.toInt(wareDto.getWareNameDtoId()));
            strings.add(Convert.toInt(wareDto.getWareAreaDtoId()));
            strings.add(Convert.toInt(wareDto.getWarePositionDtoId()));
            checkDto.setWareNameList(strings);
        }
        return AjaxResult.success(checkDto);
    }

    /**
     * 新增数据
     *
     * @param check 实体对象
     * @return 新增结果
     */
    @PostMapping
    public AjaxResult insert(@RequestBody CheckDto check) {
        AjaxResult result = Illegality(check);
        if (result != null) {
            return result;
        }
        if (ObjectUtil.isNotEmpty(check.getId())) {
            return update(check);
        }
        check.setWareMon(DateUtil.today());
        List<Integer> productNameList = check.getProductNameList();
        List<Integer> wareNameList = check.getWareNameList();
        check.setBatchId(Convert.toInt(productNameList.get(productNameList.size() - 1)));
        check.setWareId(Convert.toInt(wareNameList.get(wareNameList.size() - 1)));
        check.setWareTotalNum(check.getWareNum() + 1);
        check.setCheckId(OrderIdUtil.getOrderId());
        return checkService.save(check) ? AjaxResult.success() : AjaxResult.error();
    }

    private static AjaxResult Illegality(CheckDto check) {
        if (ObjectUtil.isEmpty(check.getGoodsType())) {
            return AjaxResult.error("类型不能为空");
        }
        if (ObjectUtil.isEmpty(check.getWareMon())) {
            return AjaxResult.error("库存月份不能为空");
        }
        if (ObjectUtil.isEmpty(check.getWareNum())) {
            return AjaxResult.error("库存数量不能为空");
        }
        if (ObjectUtil.isEmpty(check.getCreateTime())) {
            return AjaxResult.error("盘点日期不能为空");
        }
        if (ObjectUtil.isEmpty(check.getWareNameList())) {
            return AjaxResult.error("仓库不能为空");
        }
        if (ObjectUtil.isEmpty(check.getProductNameList())) {
            return AjaxResult.error("生产批号不能为空");
        }
        if (ObjectUtil.isEmpty(check.getCreateBy())) {
            return AjaxResult.error("负责人不能为空");
        }
        return null;
    }

    /**
     * 修改数据
     *
     * @param check 实体对象
     * @return 修改结果
     */
    @PutMapping
    public AjaxResult update(@RequestBody CheckDto check) {
        Check byId = checkService.getById(check.getId());
        Check check1 = new Check();

        if (!byId.getGoodsType().equalsIgnoreCase(check.getGoodsType())) {
            check1.setGoodsType(check.getGoodsType());
        }
        if (!byId.getWareMon().equalsIgnoreCase(check.getWareMon())) {
            check1.setWareMon(check.getWareMon());
        }
        if (!byId.getWareNum().equals(check.getWareNum())) {
            check1.setWareNum(check.getWareNum());
        }
        if (!byId.getCreateTime().equals(check.getCreateTime())) {
            check1.setCreateTime(check.getCreateTime());
        }
        if (!byId.getCreateBy().equalsIgnoreCase(check.getCreateBy())) {
            check1.setCreateBy(check.getCreateBy());
        }
        if (ObjectUtil.isNotEmpty(check1)) {
            check1.setId(check.getId());
            return checkService.updateById(check1) ? AjaxResult.success() : AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @DeleteMapping("{id}")
    public AjaxResult delete(@PathVariable("id") String id) {
        List<String> split = StrUtil.split(id, ",");
        return checkService.removeBatchByIds(split) ? AjaxResult.success() : AjaxResult.error();
    }
}

